package com.example.localmusic;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.localmusic.databinding.ActivityMainBinding;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener{

    ImageView nextIv, playIv, lastIv;
    TextView singerTv, songTv;
    RecyclerView RCView;
    List<musicPojo> date;
    private MusicAdapter musicAdapter;

    private int position; // 播放位置

    int currnetPlayPosition = -1; // 记录当前正在播放的音乐位置

    MediaPlayer mediaPlayer;

    // 记录暂停时播放的位置
    int currnetPausePosition = 0;

    private String[] mPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; // 权限

    PermissionUtils.onPermissionCallbackListener listener;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mediaPlayer = new MediaPlayer();
        date = new ArrayList<>();
        musicAdapter = new MusicAdapter(this, date);
        RCView.setAdapter(musicAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        RCView.setLayoutManager(linearLayoutManager);


        listener = new PermissionUtils.onPermissionCallbackListener(){

            @Override
            public void onGranted() {
                loadMusicDate();
                setEventListener();

            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
                Toast.makeText(MainActivity.this, "请运行本APP获取读取文件的权限在使用", Toast.LENGTH_LONG).show();
                System.exit(0);
            }
        };

        PermissionUtils.getInstance().onRequestPermission(this, mPermissions, listener);

    }


    /**
     * 设置recyclerview 的item点击监听
     */
    private void setEventListener() {
        musicAdapter.setListener(new MusicAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) throws IOException {
                currnetPlayPosition = position;
                playIndexMusic(position);
                playMusic();
            }
        });
    }

    /**
     * 播放指定音乐做准备
     * @param position 音乐位置
     * @throws IOException
     */
    private void playIndexMusic(int position) throws IOException {
        musicPojo musicPojo = date.get(position);
        singerTv.setText(musicPojo.getSinger());
        songTv.setText(musicPojo.getSong());
        stopMusic();
        // 重置对媒体播放器
        mediaPlayer.reset();
        // 设置新的播放器
        mediaPlayer.setDataSource(musicPojo.getPath());
    }

    /**
     * 点击播放音乐，暂停后播放音乐
     * 1.从暂停到播放
     * 2.从头播放
     * @throws IOException
     */
    private void playMusic() throws IOException {
        if (currnetPausePosition == 0) {
            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                mediaPlayer.prepare();
                mediaPlayer.start();
            }

        }else {
            mediaPlayer.seekTo(currnetPausePosition);
            mediaPlayer.start();

        }
        playIv.setImageResource(R.mipmap.icon_pause);
    }

    /**
     * 停止音乐
     */
    private void stopMusic() {
        /*停止音乐函数*/
        if (mediaPlayer != null){
            currnetPausePosition = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    /**
     * 暂停音乐
     */
    private void pauseMusic() {
        if (mediaPlayer != null&&mediaPlayer.isPlaying()) {
            currnetPausePosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.mipmap.icon_play);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    /**
     * 加载音乐数据源
     */
    private void loadMusicDate() {
//        获取ContentResolver对象
        ContentResolver resolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = resolver.query(uri, null, null, null, null, null);
        int id = 0;
        while (cursor.moveToNext()) {
            @SuppressLint("Range") String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            @SuppressLint("Range") String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            @SuppressLint("Range") String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            id++;
            String sid = String.valueOf(id);
            @SuppressLint("Range") String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            @SuppressLint("Range") long time = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
            String stime = simpleDateFormat.format(new Date(time));
            musicPojo musicPojo = new musicPojo(sid, song, singer, album, stime,path);
            date.add(musicPojo);


        }

        if (date.size() > 0){
            musicAdapter.notifyDataSetChanged();
        }


    }

    private void initView() {
        /*初始化控件*/
        nextIv = (ImageView) findViewById(R.id.music_next);
        playIv = (ImageView) findViewById(R.id.music_play);
        lastIv = (ImageView) findViewById(R.id.music_last);

        singerTv = (TextView) findViewById(R.id.music_tv_singer);
        songTv = (TextView) findViewById(R.id.music_tv_name);

        RCView = (RecyclerView) findViewById(R.id.music_rc);

        nextIv.setOnClickListener((View.OnClickListener) this);
        playIv.setOnClickListener((View.OnClickListener) this);
        lastIv.setOnClickListener((View.OnClickListener) this);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.music_last:
                if (currnetPlayPosition == -1) {
                    // 没有播放音乐
                    Toast.makeText(this, "请选择想要播放的音乐", Toast.LENGTH_LONG).show();
                    return;
                }
                if (currnetPlayPosition == 0) {
                    Toast.makeText(this, "已经是第一首了！", Toast.LENGTH_LONG).show();
                    return;
                }
                currnetPlayPosition--;
                try {
                    playIndexMusic(currnetPlayPosition);
                    playMusic();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.music_next:
                if (currnetPlayPosition == -1) {
                    // 没有播放音乐
                    Toast.makeText(this, "请选择想要播放的音乐", Toast.LENGTH_LONG).show();
                    return;
                }
                if (currnetPlayPosition == date.size()) {
                    Toast.makeText(this, "已经是最后一首了！", Toast.LENGTH_LONG).show();
                    return;
                }else {
                    currnetPlayPosition++;
                    try {
                        playIndexMusic(currnetPlayPosition);
                        playMusic();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

                break;
            case R.id.music_play:
                if (currnetPlayPosition == -1) {
                    // 没有播放音乐
                    Toast.makeText(this, "请选择想要播放的音乐", Toast.LENGTH_LONG).show();
                    return;
                }
                if (mediaPlayer.isPlaying()) {
                    // 此时音乐正在播放，需要暂停
                    pauseMusic();
                }else {
                    try {
                        playMusic();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        PermissionUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}